// 引入 gulp及组件
var gulp = require('gulp'),
    rev = require('gulp-rev'),
    revCollector  = require('gulp-rev-collector'),
    autoprefixer = require('gulp-autoprefixer'),
    less = require('gulp-less'),
    uglify = require('gulp-uglify'),
    //connect = require('gulp-connect'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-minify-css'),
    clean = require('gulp-clean'),
    gulpSequence = require('gulp-sequence'),
    replace = require('gulp-replace'),
    htmlmin = require('gulp-htmlmin'),
    browserSync = require('browser-sync').create(),   //开启服务器，实时预览
    reload = browserSync.reload,
    stripDebug = require('gulp-strip-debug'),
    removeLogs = require('gulp-removelogs'),
    babel = require("gulp-babel"),
    //增加less编译异常提醒
    notify = require('gulp-notify'),
    plumber = require('gulp-plumber'),
    imageMin = require('gulp-imagemin'),
    cheerio = require('gulp-cheerio'),
    argv = require('yargs').argv,
    px2rem = null;

var Fontmin = require('fontmin'),
    rename = require('gulp-rename');

var path = {
  src   : "src/",
  css   : "src/css/",
  js    : "src/js/",
  img   : "src/images/",
  build : "build"
};

//字体提取
var srcFont = 'src/source/*.ttf',
    destFont = 'src/fonts';
function getFonts(text) {
	var fontmin = new Fontmin();
	
	fontmin.src(srcFont)               // 输入配置
		.use(Fontmin.glyph({        // 字型提取插件
			text: text              // 所需文字
		}))
		.use(rename('fonts.ttf'))
		.use(Fontmin.ttf2eot())
		.use(Fontmin.ttf2woff())
		.use(Fontmin.ttf2svg())
		//.use(Fontmin.css())
		.dest(destFont);
    
	// 执行
	fontmin.run(function (err, files, stream) {
		if (err) {
			console.error("字体提取失败，错误信息：" + err);
		}else {
			console.log('- 字体提取成功!，字体放在文件放在' + destFont + '下，样式放在src/less目录下。');
			console.log('- 请及时修改fonts.less里，字体文件的引用路径。');
			
			//移动CSS位置
			gulp.src([destFont + '/*.css'])
				.pipe(rename("fonts.less"))
				.pipe(gulp.dest('src/less'));
            
			//删除CSS源文件
			gulp.src([destFont + '/*.css'], {read: false})
				.pipe(clean());
			
			//复制Font位置
			gulp.src('src/fonts/**.*')
				.pipe(gulp.dest('src/assets/fonts'));
        }
	});
}


gulp.task('fonts', function () {
    var text = argv.text;
    if(text && text != '') {
		getFonts(text);
		
    }else {
        console.log("完整命令：gulp fonts --text=这里输入需要提取的文字")
    }
});

gulp.task('addInfo', function(){
     return gulp.src(['dist/*.html'])
        .pipe(cheerio({
            run : function ($) {
                var nav = '',
                    footer = '',
                    style = '',
                    script = '',
                    d = new Date(),
                    time = d.getFullYear() + '年'
                        + parseInt(d.getMonth() + 1) + '月'
                        + d.getDate() +'日',
                    dev = argv.dev || "--",  //页面制作
                    des = argv.des || "--";  //页面设计

                var footBox = $("#J-foot");
                
                //添加通导通底
                if(argv['178']){
                    nav = '    <script src="http://www.178.com/s/js/nav.js" type="text/javascript"></script>';
                    footer = '<script type="text/javascript" src="http://www.178.com/s/js/footer.js"></script>';
                    style = '\n    <style>#footer{padding:20px 0;background-color:#293332;text-align:center;font-family:SimSun;line-height:26px}#footer,#footer a{color:#c1c1c1}#footer a:hover{color:#ffe56e}.all_flag{display:none}</style>\n'
                }else if(argv.ptbus){
                    nav = '    <script type="text/javascript" src="http://static.ptbus.com/newhome/head/ptbus_header.js?style=white&width=1200"></script>';
                    footer = '<script type="text/javascript" src="http://www.ptbus.com/static/common/footer.js" charset="utf-8"></script>\n';
                }else if(argv.tgbus){
                    footer = ['\n<!-- 通底区域，不要做任何处理 开始 -->\n<div class="foot"><div class="fn-wrap"><div class="copyright"><div class="about-item"><a href="http://www.tgbus.com/info/1.shtml" target="_blank">关于我们</a> <a href="http://www.tgbus.com/info/2.shtml" target="_blank">广告投放</a> <a href="http://www.tgbus.com/info/3.shtml" target="_blank">联系我们</a> <a href="http://www.tgbus.com/info/4.shtml" target="_blank">网站地图</a> <a href="http://www.tgbus.com/info/5.shtml" target="_blank">友情链接</a> <a href="http://www.tgbus.com/info/6.shtml" target="_blank">诚聘英才</a> <a href="http://user.tgbus.com/" target="_blank">成为会员</a> <a href="http://www.tgbus.com/info/8.shtml" target="_blank">版权声明</a> <a href="http://wap.tgbus.com/" target="_blank">WAP手机版</a> <a href="http://shop.tgbus.com/" target="_blank">购物热线:4006-577-566</a></div><div class="copyright-item"><p><a href="http://www.miibeian.gov.cn/">渝ICP备14007792号-12</a> <a href="javascript:;">渝B2-20150036 渝网文（2015）1003-002号</a> <a href="javascript:;">渝公网安备 50019002500480号</a></p><p><span>Copyright © 2004-2017 TGBUS Corporation, All Rights Reserved.</span></p></div></div></div></div>\n<!-- 通底区域，不要做任何处理 结束 -->'].join("");
                    nav = ['\n<!-- 通导区域，不要做任何处理 开始 -->\n<div class="body-wrap"><div class="top-navbar"><div class="top-navbar-inner"><div class="top-navbar-left"><a class="top-navbar-logo" href="http://www.tgbus.com/" target="_blank"></a> <a class="top-navbar-weibo" href="http://weibo.com/tgbusvip" target="_blank">官方微博</a> <a class="top-navbar-client" href="http://ps4.tgbus.com/app/" target="_blank">手机客户端</a></div><div class="top-navbar-right"><a class="top-navbar-login" onClick="showlogin();" id="denglu" href="javascript:;">登录</a> <span id="u_info" style="margin-left:20px"></span> <a class="top-navbar-reg" id="zhuce" href="http://user.tgbus.com/reg/mobile.html" target="_blank">注册</a></div></div></div><div class="popup" id="hide_msg" style="display:none"><div class="hd"><a href="javascript:" onClick="$(\'#username_div\').val(\'\');$(\'#password_div\').val(\'\');$(\'#hide_msg\').hide()" class="close" title="关闭窗口">✕</a></div><div class="bd" id="bdcontent"><div class="login fl"><a class="ab starGame" style="position:absolute" href="http://user.tgbus.com/api/url.ashx?app=stargame&redirect_uri=http://user.tgbus.com/index1.html"><img src="http://www.tgbus.com/images/stargame_01.gif"></a><h3>用户登录</h3><div class="zhsr"><label for="uesrname">账号：</label><input type="text" name="username_div" id="username_div" onKeyDown="if(event.keyCode==13){login();}" placeholder="请输入账号" class="mail_zh"></div><div class="zhsr"><label for="password">密码：</label><input placeholder="请输入密码" type="password" name="password_div" id="password_div" onKeyDown="if(event.keyCode==13){login();}" class="password_zh"></div><div class="zhsr" style="margin-left:150px;text-align:center;margin-bottom:10px"><script async defer type="text/javascript" src="http://api.geetest.com/get.php?gt=c666d711f59e5bda7b2341423987b36b"></script></div><div class="c_login1"><button id="btnLogin" type="button" style="cursor:pointer" onClick="login()">登 录</button></div><div class="c_reg1">没有巴士通行证？<a href="http://user.tgbus.com/register.aspx" target="_blank">现在注册</a>！ 无法正常登陆？<a href="http://bbs.tgbus.com/member.php?mod=logging&action=login" target="_blank">请点击此处</a></div></div></div><div class="bd bdhide" id="bdhide"><div class="login f2">登录中，请稍后... <img src="http://ol.tgbus.com/css/images/dt_loading_nobg.gif" alt="登录中..."></div></div></div></div>\n<!-- 通导区域，不要做任何处理 结束 -->'].join("");
                    style = '\n    <link type="text/css" rel="styleSheet" href="http://shouji.tgbus.com/css/2016_v1/css/top-navbar.css">\n    <link rel="stylesheet" type="text/css" href="http://www.tgbus.com/login.css?t=2.0">\n    <link href="http://shouji.tgbus.com/css/2016_v1/css/common.css" rel="stylesheet" type="text/css">';
                    script = '\n    <script src="http://shouji.tgbus.com/js/currency/tg_login.js"></script>';

                    $("body").prepend(nav);
                    footBox.replaceWith(footer);
                    $("title").after(style);
                    $("head").append(script);

                    nav = '';
                    style = '';
                    footer = '';
                }

                $("head").append(nav + style);
                $("body").append(footer);
                footBox.remove();
                $('html').after('\n<!-- 页面设计：'+ des +' | 页面制作：'+ dev +' | 创建：'+ time +' -->');
                
                if(argv.v){
					var $link = $("link"),
						$script = $("script"),
						_src = null,
						$item = null;
	
					$link.each(function (index,item) {
						$item = $(item);
						_src = $item.attr("href");
						if(!_src || _src.indexOf("http") >= 0) return true;
						_src = _src.replace(/(\?.*)/, '') + '?t=' + d.valueOf();
						$item.attr("href", _src);
					});
	
					$script.each(function (index,item) {
						$item = $(item);
						_src = $item.attr("src");
						if(!_src || _src.indexOf("http") >= 0) return true;
						_src = _src.replace(/(\?.*)/, '') + '?t=' + d.valueOf();
						$item.attr("src", _src);
					})
                }
            },
            parserOptions: {
                decodeEntities : false
            }
        }))
        .pipe(gulp.dest('dist/'));
});

gulp.task('imgMin', function () {
     return gulp.src(path.img + "*.*")
        .pipe(imageMin({
            progressive: true
        }))
        .pipe(gulp.dest('dist/assets/images/'))
});


gulp.task('clean', function () {
    return gulp.src(['dist/','output/'])
        .pipe(clean());
});

gulp.task('jsconcat',function () {
    return gulp.src([
        'src/js/plugins/*.js'])
        .pipe(concat('plugins.js'))//合并后的文件名
        .pipe(gulp.dest('output/'));
});

gulp.task('jsconcat-plugin',function () {
    return gulp.src([
        'src/js/vendor/rely-*.js',
        'src/js/vendor/plug-*.js'
        ])
        .pipe(concat('vendor.js'))//合并后的文件名
        .pipe(gulp.dest('output/'));
});

gulp.task('jsconcat-dev',function () {
    return gulp.src([
        'src/js/plugins/*.js',
        'src/js/core/*.js'
        ])
        .pipe(concat('plugins.js'))//合并后的文件名
        .pipe(gulp.dest('src/assets/js'));
});

gulp.task('jsconcat-plugin-dev',function () {
    return gulp.src([
        'src/js/vendor/rely-*.js',
        'src/js/vendor/plug-*.js'
        ])
        .pipe(concat('vendor.js'))//合并后的文件名
        .pipe(gulp.dest('src/assets/js'));
});


gulp.task('jsmin',function () {
    return gulp.src('output/*.js')
    //.pipe(stripDebug())
        .pipe(removeLogs())
        .pipe(uglify({
        }))
        .pipe(gulp.dest('output/'))
});


// gulp.task('jsRev', function () {
//     return gulp.src('output/js/*.js')
//         .pipe(rev())
//         .pipe(gulp.dest('dist/js'))
//         .pipe(rev.manifest({
//             base: 'dist/css',
//             merge: true // merge with the existing manifest (if one exists)
//         }))
//         .pipe(gulp.dest('output/rev'));
// });


gulp.task('cssmin', function () {
    return gulp.src('output/*.css')
        .pipe(cssmin())
        .pipe(gulp.dest('output/'))
});


if(argv['rem']){
    px2rem = require('gulp-px2rem-plugin');
}

gulp.task('cssconcat',function () {
    var val =gulp.src('src/css/*.css')
            .pipe(concat('base.css'));
    if(argv['rem']){
        val.pipe(px2rem({'width_design':750,'valid_num':4,'pieces':10,'ignore_px':[1,2],'ignore_selector':['@media']}))
    }
    return val.pipe(gulp.dest('output/'));
});

gulp.task('cssconcat-plugin',function () {
    var val =gulp.src('src/css/plugins/*.css')
        .pipe(concat('plugin.css'));
    if(argv['rem']){
        val.pipe(px2rem({'width_design':750,'valid_num':4,'pieces':10,'ignore_px':[1,2],'ignore_selector':['@media']}))
    }
    return val.pipe(gulp.dest('output/'));
});

gulp.task('cssconcat-dev',function () {
    var val =gulp.src('src/css/*.css')
        .pipe(concat('base.css'));
    if(argv['rem']){
        val.pipe(px2rem({'width_design':750,'valid_num':4,'pieces':10,'ignore_px':[1,2],'ignore_selector':['@media']}))
    }
    return val.pipe(gulp.dest('src/assets/css'));
});
gulp.task('cssconcat-dev-plugin',function () {
    var val =gulp.src('src/css/plugins/*.css')
        .pipe(concat('plugin.css'));
    if(argv['rem']){
        val.pipe(px2rem({'width_design':750,'valid_num':4,'pieces':10,'ignore_px':[1,2],'ignore_selector':['@media']}))
    }
    return val.pipe(gulp.dest('src/assets/css'));
});

gulp.task('cssRev', function () {
    if(argv.v) {
		return gulp.src(['output/*.css','output/*.js'])
			.pipe(gulp.dest('output/'))
			.pipe(gulp.dest('output/assets'));
    }else {
		return gulp.src(['output/*.css','output/*.js'])
			.pipe(gulp.dest('output/'))
			.pipe(rev())
			.pipe(gulp.dest('output/assets'))
			.pipe(rev.manifest())
			.pipe(gulp.dest('output/rev'));
    }
});

gulp.task('movejs', function(){
  return gulp.src('output/assets/*.js')
  .pipe(gulp.dest('dist/assets/js/'));
});

gulp.task('movecss', function(){
  return gulp.src('output/assets/*.css')
  .pipe(gulp.dest('dist/assets/css/'));
});

gulp.task('movefonts', function(){
	return gulp.src('src/fonts/**.*')
		.pipe(gulp.dest('dist/assets/fonts'));
});

// gulp.task("es6", function () {
//     return gulp.src("src/assets/js/**/*.*")
//         .pipe(babel({
//             presets: ['es2015']
//         }))
//         .pipe(gulp.dest("src/assets/js/"));
// });



gulp.task('htmlmin', function () {
    var options = {
        removeComments: false,//清除HTML注释
        collapseWhitespace: false,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    return gulp.src('dist/*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist/'));
});

// gulp.task('rev',function(){
//     gulp.src('src/*.html')
//         .pipe(rev())
//         .pipe(gulp.dest('dist/'));
       
// })

gulp.task('rev', function () {
    return gulp.src(['output/rev/*.json','src/*.html'])
        .pipe( revCollector({
            
            
        }) )
        .pipe( gulp.dest('dist/') );
});

gulp.task('less', function () {
    return gulp.src(['src/less/*.less','src/less/_modules/*.less'])
        //错误提示
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(less())
        //.on('error', handleError)
        .pipe(gulp.dest('src/css'));
});

/*function handleError(err) {
  if (err.message) {
    console.log(err.message)
  } else {
    console.log(err)
  }
  this.emit('end')
}*/


var filesToMove = [
    'src/images/**/*.*'
];

gulp.task('dist', function () {
    return gulp.src(filesToMove)
        .pipe(gulp.dest('dist/assets/images'));
});

gulp.task('dist-dev', function () {
    return gulp.src('src/images/**/*.*')
        .pipe(gulp.dest('src/assets/images'));
});

gulp.task('dist-js-dev', function () {
    return gulp.src('src/js/page/*.*')
        .pipe(gulp.dest('src/assets/js/page/'));
});

gulp.task('move-page-js', function () {
    return gulp.src('src/js/page/*.*')
    //.pipe(stripDebug())
        .pipe(removeLogs())
        .pipe(uglify())
        .pipe(gulp.dest('dist/assets/js/page/'))
});

gulp.task('replace', function(){
    return gulp.src('dist/*.html')
        .pipe(replace('src="images/','src="assets/images/'))
        .pipe(gulp.dest('dist/'));
});

gulp.task('replace-sec', function(){
    return gulp.src('dist/*.html')
        .pipe(replace('src="./images/','src="assets/images/'))
        .pipe(gulp.dest('dist/'));
});

gulp.task('distres', function () {
    return gulp.src('src/resources/**.*')
        .pipe(gulp.dest('dist/resources'))
});

gulp.task('AutoFx', function () {
    return gulp.src('dist/css/*.css')
        .pipe(autoprefixer({
            browsers: ['last 2 versions','Android >= 4.0'],
            cascade: true, //是否美化属性值 默认：true 像这样：
            //-webkit-transform: rotate(45deg);
            //        transform: rotate(45deg);
            remove:true //是否去掉不必要的前缀 默认：true 
        }))
        .pipe(gulp.dest('dist/css'));
});

//reload server
// gulp.task('reload-dev',function() {
//   return gulp.src(['src/images/**/*.*',
//                 'src/js/**/*.*',
//                 'src/less/**/*.*',
//                 'src/resources/**/*.*',
//                 'src/*.html'
//         ])
//     .pipe(reload);
// });

// gulp.task('connectDev', function() {
//   connect.server({
//     root: 'src',
//     port: 8000,
//     livereload: true
//   });
// });

gulp.task('connectDev', function() {
    browserSync.init({
        server: "src",   //服务器根目录
        port: 8000
    });
    gulp.watch(['src/images/**/*.*',
                'src/js/**/*.*',
                'src/less/**/*.*',
                'src/resources/**/*.*',
                'src/*.html'
        ],['dev-re', reload]);
});

gulp.task('connectDev-less', function() {
    browserSync.init({
        server: "src",   //服务器根目录
        port: 8000
    });
    gulp.watch(['src/images/**/*.*',
                'src/js/**/*.*',
                'src/less/**/*.*',
                'src/resources/**/*.*',
                'src/*.html'
        ],['dev-re-less', reload]);
});

//gulp.task('build', ['clean','jsconcat','jsmin']);

gulp.task('build', gulpSequence('clean','jsconcat','jsconcat-plugin','jsmin','cssconcat','cssconcat-plugin','cssmin','cssRev','movejs','movecss','AutoFx',['dist','distres','rev'],'htmlmin','replace','replace-sec','move-page-js','movefonts','addInfo'));

//gulp.task('dev', ['connectDev', 'watch','less']);

// gulp.task('dev', gulpSequence('clean','jsconcat','cssconcat','cssRev',['dist','rev'],'connectDev', 'watch'));

gulp.task('dev-re',function(callback){
     gulpSequence('less','jsconcat-dev','jsconcat-plugin','cssconcat-dev','cssconcat-dev-plugin','dist-dev','dist-js-dev')(callback);
});

gulp.task('dev-re-less',function(callback){
     gulpSequence('less','jsconcat-dev','jsconcat-plugin','cssconcat-dev','dist-dev')(callback);
});

gulp.task('default', ['build']);

// gulp.task('watch', function() {
//     gulp.watch(path.src + '**/*.*',['dev-re','rev','less','reload-dev']);
// });

gulp.task('dev', gulpSequence('connectDev','jsconcat-dev','jsconcat-plugin-dev','cssconcat-dev','dist-dev'));
gulp.task('dev-less', gulpSequence('connectDev-less','less','jsconcat-dev','jsconcat-plugin-dev','cssconcat-dev','dist-dev'));
// gulp.task('watch', function() {
//     gulp.watch(['src/images/**/*.*',
//                 'src/js/**/*.*',
//                 'src/less/**/*.*',
//                 'src/resources/**/*.*',
//                 'src/*.html'
//         ],['reload-dev','dev-re']);
// });
